﻿

function isFunction(a) {
    return typeof a == 'function';
}
//通过唯一ID得到对象
function oo(v) {
    return document.getElementById(v);
}
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}
var topScr = 1;
var topWidth = 400;
var topHeight = 110; //by 赵国伟 扩充；

var prePopDivName = "pop-";  //by 赵国伟 扩充；
var fullPopDivName = prePopDivName + "Divsinfo";  //by 赵国伟 扩充；

var IsShowTaskTipDiv = true;
function createTaskTipDiv(tipType) {

    if (!IsShowTaskTipDiv)
        return;
    var tips = "<img src=\"/Manage/Images/loading.gif\" width=18 height=18 align=absbottom> ";
    if (tipType == null || tipType == "" || tipType == "task")
        tips += "任务处理中,请稍候...";
    else if (tipType == "load")
        tips += "数据加载中,请稍候...";
    else
        tips += tipType;
    var obj = null;
    var top = "";
    if (window.screen.width <= 1024) {
        top = (getScrollTop() + 200) + "px";
    }
    else {
        top = (getScrollTop() + 280) + "px";

    }

    if (oo("TaskTipDiv") != null) {
        oo("TaskTipDiv").style.top = top;
        oo("TaskTipDiv").style.display = "";
    }
    else {
        obj = document.createElement("div");
        obj.setAttribute("id", "TaskTipDiv");
        obj.style.position = "absolute";
        obj.style.left = ((document.body.scrollWidth / 2) - 82) + "px";
        obj.style.top = top;
        obj.style.zIndex = "10009";
        document.body.appendChild(obj)
        var content = "";
        content += "<iframe src=\"about:blank\" style=\" position:absolute; visibility:inherit; top:0px; left:0px; width:147px; height:34px; z-index:-1; filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"></iframe>";
        content += "<div style=\"z-index:10009;padding:7px; border:1px solid #DCBE6E;background:#FFFFBF; \">" + tips + "</div>"
        obj.innerHTML = content;
    }

}

function deleteTaskTipDiv() {
    if (!IsShowTaskTipDiv)
        return;
    if (oo("TaskTipDiv") != null) {
        oo("TaskTipDiv").style.display = "none";
    }
}
var bgDivBackgroundColor = "#000";
function createBgDiv() {
    var sWidth, sHeight;
    sWidth = document.body.clientWidth;
    if (sWidth < 1000) {
        sWidth += 20;
    }
    sHeight = document.body.scrollHeight;
    if (sHeight < window.screen.height) sHeight = window.screen.height;
    var bgObj = null;
    if (isObject(oo("bgDiv"))) {
        bgObj = oo("bgDiv");
    }
    else {
        bgObj = document.createElement("div");
        bgObj.setAttribute('id', 'bgDiv');
        bgObj.style.position = "absolute";
        bgObj.style.top = "0";
        bgObj.style.background = bgDivBackgroundColor;
        bgObj.style.filter = "alpha(opacity=35);-moz-opacity: 0.6;opacity: 0.6;";
        bgObj.style.opacity = "0.5";
        bgObj.style.left = "0";
        bgObj.style.width = sWidth + "px";
        bgObj.style.height = sHeight + "px";
        bgObj.style.zIndex = "10000";
        document.body.appendChild(bgObj);
    }
    bgObj.innerHTML = "<iframe src=\"\" style=\"position:absolute; visibility:inherit; top:0px; left:0px; width:100%; height:100%; z-index:-1; filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"></iframe>";

}
var color = "#009933";
function oodiv(bordercolor) {
    
    var pWidth, pHeight, top, left;
    pWidth = topWidth;
    pHeight = topHeight;
    top = 200;
    color = bordercolor;
    if (topScr < 1) {
        if (typeof window.pageYOffset != 'undefined') {
            topScr = window.pageYOffset;
        }
        else if (typeof document.compatMode != 'undefined' &&
			 document.compatMode != 'BackCompat') {
            topScr = document.documentElement.scrollTop;
        }
        else if (typeof document.body != 'undefined') {
            topScr = document.body.scrollTop;
        }
    }
    if (topScr > 0) {
        top = (window.screen.availHeight - pHeight) / 3 + topScr;
    }
    else {
        top = document.body.clientHeight - 400;
    }
    left = (document.body.clientWidth - pWidth) / 2;
    var sPopup = null;
    if (isObject(oo(fullPopDivName))) {
        sPopup = oo(fullPopDivName);
        document.body.removeChild(sPopup);
    }
    sPopup = document.createElement('div');
    sPopup.setAttribute('id', fullPopDivName);
    sPopup.style.position = "absolute";
    sPopup.style.top = (getScrollTop() + top) + "px";
    sPopup.style.left = left + "px";
    sPopup.style.padding = "10px";
    sPopup.style.background = "#FFFFFF";
    sPopup.style.border = color + " 1px solid";
    sPopup.style.display = '';
    sPopup.style.zIndex = "10002";
    document.body.appendChild(sPopup);
    return sPopup;
}
function createTable() {
    var mess = "";
    mess = "<table style=\"border-width:0px 0 0 0px;\" width='" + topWidth + "' border='0' align='center' cellpadding='0' cellspacing='0' id='popTable'>";
    mess += "<tr><td height='20' class=\"td1\" width=\"95%\" style='border-bottom:solid 1px #ccc;cursor:move;border-width:0px 0 1 0px;' onMouseDown=\"javascript:moveStart(event,fullPopDivName);\" ><b style='font-size:14px;color:#009933'>$title$</b></td><td align='right' valign='top' style='border-bottom:solid 1px #ccc;border-width:0px 0 1 0px;' >";
    mess += "<a href='javascript:yesOther(false);' title='关闭'><img src='/Manage/Images/close.gif' border='0' align='absmiddle'></a></td></tr>";
    mess += "<tr><td style='padding:5px;'colspan=2 style=\"border-width:0px 0 0 0px;\">";
    mess += "$info$</td></tr>" +
	"<tr><td colspan=2 height='20' align=right style=\"border-width:0px 0 0 0px;\"><span style='color:#999'>&copy;" + ShoppingName + "</span></td></tr>" +
	"</table>";
    return mess;
}


function execInforeturn(istrue, info, status) {
    createBgDiv();
    if (!istrue) color = "#ff0000";
    var sPopup = oodiv(color);
    //处理消息
    var mess = "";
    if (istrue) {
        mess = "系统信息";
        mess = "<table style=\"border-width:0px 0 0 0px;\" width='400' id='" + fullPopDivName + "' border='0' align='center' cellpadding='0' cellspacing='0'>" +
		   "<tr><td width=\"380\" height='20' style='border-bottom:solid 1px #ccc;cursor:move;border-width:0px 0 1 0px;' onMouseDown=\"javascript:moveStart(event,fullPopDivName);\" ><b style='font-size:14px;color:#009933'>" + mess +
		   "</b></td><td align='right' valign='top' style='border-bottom:solid 1px #ccc;border-width:0px 0 1 0px;'>";
    }
    else {
        mess = "错误提示";
        mess = "<table style=\"border-width:0px 0 0 0px;\" width='400' id='" + fullPopDivName + "' border='0' align='center' cellpadding='0' cellspacing='0'>" +
		   "<tr><td width=\"380\" height='20' style='border-bottom:solid 1px #ccc;cursor:move;border-width:0px 0 1 0px;' onMouseDown=\"javascript:moveStart(event,fullPopDivName);\" ><b style='font-size:14px;color:#ff0000'>" + mess +
		   "</b></td><td align='right' valign='top' style='border-bottom:solid 1px #ccc;border-width:0px 0 1 0px;' >";
    }
    if (status == 1) mess += "<a href='javascript:yesOther(true);' title='关闭'><img src='../Images/close.gif' border='0' align='absmiddle'></a></td></tr>";
    else mess += "</td></tr>";
    mess += "<tr><td colspan=2 style=\"border-width:0px 0 0 0px;\"><br><span style='color:'>";
    if (info.indexOf("...") > -1) mess += "<img  align='absmiddle' src='/Manage/Images/loading.gif'>&nbsp;&nbsp;";
    mess += info + "</SPAN><br><br>";
    mess += "</td></tr>" +
	"<tr><td colspan=2 height='20' align=right style=\"border-width:0px 0 0 0px;\" ><span style='color:#999'>&copy; 盛拓传媒</span></td></tr>" +
	"</table>";
    sPopup.innerHTML = mess;
}


function yesOther(t) {

    var IsHavePopDiv = false;
    var lastDivName = "";
    var divs = document.getElementsByTagName("DIV");
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].id.indexOf(prePopDivName) >= 0) {
            fullPopDivName = divs[i].id;
        }
    }
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].id.indexOf(prePopDivName) >= 0 && divs[i].id != fullPopDivName) {
            oo(divs[i].id).style.display = "";
            IsHavePopDiv = true;
        }
    }
    if (!t) {
        var bgObj2 = document.getElementById(fullPopDivName);
        document.body.removeChild(bgObj2);
        if (!IsHavePopDiv) {
            var bgObj = document.getElementById("bgDiv");
            document.body.removeChild(bgObj);
        }
    }
    else {
        var bgObj2 = document.getElementById(fullPopDivName);
        document.body.removeChild(bgObj2);
        if (!IsHavePopDiv) {
            var bgObj = document.getElementById("bgDiv");
            document.body.removeChild(bgObj);
        }
    }
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].id.indexOf(prePopDivName) >= 0) {
            fullPopDivName = divs[i].id;
        }
    }
}
//提示窗口可拖动  开始
function moveStart(event, _sId) {
    var oObj = document.getElementById(_sId);
    oObj.onmousemove = mousemove;
    oObj.onmouseup = mouseup;
    oObj.setCapture ? oObj.setCapture() : function () { };
    oEvent = window.event ? window.event : event;
    var dragData = { x: oEvent.clientX, y: oEvent.clientY };
    var backData = { x: parseInt(oObj.style.top), y: parseInt(oObj.style.left) };

    function mousemove() {
        var oEvent = window.event ? window.event : event;
        var iLeft = oEvent.clientX - dragData["x"] + parseInt(oObj.style.left);
        var iTop = oEvent.clientY - dragData["y"] + parseInt(oObj.style.top);
        oObj.style.left = iLeft;
        oObj.style.top = iTop;
        dragData = { x: oEvent.clientX, y: oEvent.clientY };
    }

    function mouseup() {
        var oEvent = window.event ? window.event : event;
        oObj.onmousemove = null;
        oObj.onmouseup = null;
        if (oEvent.clientX < 1 || oEvent.clientY < 1 || oEvent.clientX > document.body.clientWidth || oEvent.clientY > document.body.clientHeight) {
            oObj.style.left = backData.y;
            oObj.style.top = backData.x;
        }
        oObj.releaseCapture ? oObj.releaseCapture() : function () { };
    }
}

///判断是否为浮点数
function IsRate(input) {
    var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字     //判断正整数 /^[1-9]+[0-9]*]*$/   
    if (!re.test(input)) {
        return false;
    }
    return true;
}

//提示窗口可拖动  结束 
function isMoney(t) {
    if (t == "") return false;
    var value = new String(t);
    var l = value.length;
    var x = value.indexOf('.', 0);
    if (value.indexOf('.', x + 1) > 0) {
        return false;
    }
    else {
        if (x > 0) {
            if (l - x > 3 || l - x == 1) {
                return false;
            }
            else {
                var bef = value.substring(0, x);
                var aft = value.substring(x + 1, l);
                var flag = false;
                var exp = /[^0-9()-]/;
                if (bef.search(exp) != -1) {
                    flag = true;
                }
                if (aft.search(exp) != -1) {
                    flag = true;
                }
                if (flag) {
                    return false;
                }
                else {
                    return true;
                }
            }
        }
        else {
            var exp = /[^0-9()-]/;
            if (value.search(exp) != -1) {
                return false;
            }
            return true;
        }
    }
}
function getRadioValue(name) {
    var radioes = document.getElementsByName(name);
    for (var i = 0; i < radioes.length; i++) {
        if (radioes[i].checked) {
            return radioes[i].value;
        }
    }
    return "";
}




//=======================以下为 赵国伟 2009/10/15 补充的一些公共方法 ==================================

var IsLoadRunTips = true; //是否显示加载提示。
//Jquery框架下的Ajax全局设置； by 赵国伟 2010-09-21；
$.ajaxSetup(
    {
        cache: false,
        beforeSend: function () {
            if (IsLoadRunTips) createTaskTipDiv();
        },
        complete: function () {
            if (IsLoadRunTips) deleteTaskTipDiv();
        },
        error: function (e) {
            alert("请求服务器端接口失败！请刷新重试或与管理员联系！" + e);
        }
    }
  );

//获得指定参数的弹出层；by 赵国伟 2009/10/15;
//width:层的宽度；height:高度；borderColor:边框颜色,title:标题；content:层内容；
function GetPopupDiv(width, height, borderColor, title, content, divname, isHideDDlControl, isCreateBgDiv) {

    if (isHideDDlControl == null)
        isHideDDlControl = true;
    if (isCreateBgDiv == null)
        isCreateBgDiv = true;
    if (divname != null)
        fullPopDivName = prePopDivName + divname;
    var divs = document.getElementsByTagName("DIV");
    for (var i = 0; i < divs.length; i++) {
        //alert(divs[i].id);
        if (divs[i].id.indexOf(prePopDivName) >= 0) {
            oo(divs[i].id).style.display = "none";
        }
    }
   
    topWidth = width; //设置宽度(该变量为全局变量)；
    topHeight = height; //设置高度(该变量为全局变量)；
    if (isCreateBgDiv)
        createBgDiv(); //创建Div背景，目的：遮住当前页面；
    var table = createTable(); // 创建窗体Table; 后面设置好改窗体的相关内容后将 添加到即将创建的浮框层中。
    table = table.replace("$title$", title);  //设置窗体标题；
    table = table.replace("$info$", content); //设置表单内容；
    var divPopup = oodiv(borderColor); //创建指定边框颜色的浮框；
    divPopup.innerHTML = table;  //表单内容加入到弹出的层中；
}


///将日期字符串转化为UTC秒数 by 赵国伟 2009/10/15 注：在生成json结构的时候常常需要将其中的日期字段
///转化为UTC形式，因为在服务器端.net Josn反序列化的时候必须采用此格式；
function DateStringToUTC(str) {
    var arys = new Array();
    arys = str.split('-');
    var newDate = new Date(arys[0], arys[1] - 1, arys[2]);
    newDate.setHours(newDate.getHours() + 8);
    return newDate.getTime();
}

///将当前日期转化为UTC形式； by 赵国伟 2009/10/15 
function CurrentDateStringToUTC() {
    var newDate = new Date();
    newDate.setHours(newDate.getHours() + 8);
    return newDate.getTime();
}

///设置下拉列表默认值；by 赵国伟；
function SetddlObject(obj, defaultValue) {
    // alert(defaultValue);
    for (i = 0; i < $(obj).options.length; ++i) {
        //alert($(obj).options[i].value);
        if (oo(obj).options[i].value == defaultValue) {
            oo(obj).options[i].selected = true;
            oo(obj).options[i].defaultSelected = true;
        }
    }
}

Date.prototype.format = function (formatter) {
    if (!formatter || formatter == "") {
        formatter = "yyyy-MM-dd";
    }
    var year = this.getYear().toString();
    var month = (this.getMonth() + 1).toString();
    var day = this.getDate().toString();

    var hour = this.getHours().toString();
    var min = this.getMinutes().toString();
    var sec = this.getSeconds().toString();

    var yearMarker = formatter.replace(/[^y|Y]/g, '');
    if (yearMarker.length == 2) {
        year = year.substring(2, 4);
    }
    var monthMarker = formatter.replace(/[^M]/g, '');
    if (monthMarker.length > 1) {
        if (month.length == 1) {
            month = "0" + month;
        }
    }

    var dayMarker = formatter.replace(/[^d]/g, '');
    if (dayMarker.length > 1) {
        if (day.length == 1) {
            day = "0" + day;
        }
    }

    var hourMarker = formatter.replace(/[^H|h]/g, '');

    if (hourMarker.length > 1) {
        if (hour.length == 1) {
            hour = "0" + hour;
        }
    }

    var minMarker = formatter.replace(/[^m]/g, '');
    if (minMarker.length > 1) {
        if (min.length == 1)
            min = "0" + min;
    }
    var secMarker = formatter.replace(/[^s|s]/g, '');
    if (secMarker.length > 1) {
        if (sec.length == 1)
            sec = "0" + sec;
    }


    if (yearMarker != "")
        formatter = formatter.replace(yearMarker, year);
    if (monthMarker != "")
        formatter = formatter.replace(monthMarker, month);
    if (dayMarker != "")
        formatter = formatter.replace(dayMarker, day);

    if (hourMarker != "")
        formatter = formatter.replace(hourMarker, hour);
    if (minMarker != "")
        formatter = formatter.replace(minMarker, min);
    if (secMarker != "")
        formatter = formatter.replace(secMarker, sec);

    return formatter;
}

///将Json格式的Date转化为正常的日期格式；by 赵国伟；
function ConvertJsonDatetoToLocateDate(jsonDate) {
    jsonDate = jsonDate.replace("/Date(", "").replace(")/", "");
    var d = new Date(parseInt(jsonDate));
    return d.pattern("yyyy-MM-dd");
}
function ConvertJsonDatetoToLocateDate2(jsonDate) {
    jsonDate = jsonDate.replace("/Date(", "").replace(")/", "");
    var d = new Date(parseInt(jsonDate));
    return d.format("yyyy-MM-dd hh:mm:ss");

}
///将复选框全部选中或者取消；by 赵国伟；
function checkAll(objForm) {
    for (var i = 0; i < oo(objForm).elements.length; i++) {
        var e = oo(objForm).elements[i];
        if (e.name != 'chkall') {
            e.checked = oo(objForm).chkall.checked;
        }
    }

}

///通过指定复选框控件的选中状态  来控制另外指定复选框控件的状态； by 赵国伟；
function checkAllCheckButton(checkName, switchName) {
    var status = document.getElementById(switchName).checked;
    if (document.getElementsByName(checkName) != null) {
        for (var i = 0; i < document.getElementsByName(checkName).length; ++i) {
            document.getElementsByName(checkName)[i].checked = status;
        }
    }
}


///获取指定复选框的选中值； by 赵国伟 2010-04-02;
function GetCheckObjectValues(chkName) {
    var selectValues = "";
    if (document.getElementsByName(chkName) != null) {
        for (var i = 0; i < document.getElementsByName(chkName).length; ++i) {
            if (document.getElementsByName(chkName)[i].checked) {
                if (selectValues == "")
                    selectValues = document.getElementsByName(chkName)[i].value;
                else
                    selectValues += "," + document.getElementsByName(chkName)[i].value;
            }
        }
    }
    return selectValues;
}
///获取指定复选框的选中值；并存为数组 by 赵国伟 2012-04-07
function GetCheckObjectValuesToArray(chkName) {
    var result = new Array();
    if (document.getElementsByName(chkName) != null) {
        for (var i = 0; i < document.getElementsByName(chkName).length; ++i) {
            if (document.getElementsByName(chkName)[i].checked) {
                result.push(document.getElementsByName(chkName)[i].value);
            }
        }
    }
    return result;
}

///设置指定复选框的默认值； by 赵国伟 2010-04-02;
function SetCheckObjectDefaultValue(chkName, defaultValue) {
    defaultValue = "," + defaultValue + ",";
    if (document.getElementsByName(chkName) != null) {
        for (var i = 0; i < document.getElementsByName(chkName).length; ++i) {
            if (defaultValue.indexOf("," + document.getElementsByName(chkName)[i].value + ",") >= 0) {
                document.getElementsByName(chkName)[i].checked = true;
            }
        }
    }
}


///将数字格式化成价格显示方式；by 赵国伟；2010-09-02 做了修正： 传入参数为负数时输出不正确
function ConvertToMoeny(s) {
    if (/[^0-9\.\-]/.test(s)) return "";
    s = ForDight(s, 2).toString();

    s = s.replace(/^[-]{1}(\d*)$/, "-$1.");
    s = s.replace(/^(\d*)$/, "$1.");
    s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    s = s.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(s))
        s = s.replace(re, "$1,$2");
    s = s.replace(/,(\d\d)$/, ".$1");
    return s.replace(/^\./, "0.")
}

///将星期转化为数字； by 赵国伟；
function GetWeekNum(weekName) {
    var weekNum = -1;
    switch (weekName) {
        case "Monday":
            weekNum = 0;
            break;
        case "Tuesday":
            weekNum = 1;
            break;
        case "Wednesday":
            weekNum = 2;
            break;
        case "Thursday":
            weekNum = 3;
            break;
        case "Friday":
            weekNum = 4;
            break;
        case "Saturday":
            weekNum = 5;
            break;
        case "Sunday":
            weekNum = 6;
            break;
    }
    return weekNum;
}
///将指定的字符串装化为日期格式对象；by 赵国伟；
function ConverToDate(str) {
    var arys = new Array();
    arys = str.split('-');
    var NowDate = new Date(arys[0], arys[1], arys[2]);
    return NowDate;
}

///向指定的日期字符串中 增加天数   by 赵国伟；
function GetNextMonthFirstDay(dateStr) {
    var arys = new Array();
    arys = dateStr.split('-');
    var nowdate = new Date(arys[0], arys[1] - 1, arys[2]);
    var year = (nowdate.getYear() < 1900 ? (1900 + nowdate.getYear()) : nowdate.getYear())
    var MonthNextFirstDay = new Date(year, nowdate.getMonth() + 1, 1);
    return (MonthNextFirstDay.getFullYear() + "-" + parseInt(MonthNextFirstDay.getMonth() + 1) + "-" + MonthNextFirstDay.getDate());

}

///获得当前日期所在的月份的最后一天  by 赵国伟；
function GetMonthLastDay(datestr) {
    var arys = new Array();
    arys = datestr.split('-');
    var nowdate = new Date(arys[0], arys[1], "01");
    var year = (nowdate.getYear() < 1900 ? (1900 + nowdate.getYear()) : nowdate.getYear())
    var MonthNextFirstDay = new Date(year, nowdate.getMonth(), 1);
    var MonthLastDay = new Date(MonthNextFirstDay - 86400000);
    return MonthLastDay;

}

///获得两个日期相差的天数；by 赵国伟；
function GetDifferentDays(startDate, endDate) {

    fArray = startDate.split("-");
    sArray = endDate.split("-");
    var fDate = new Date(fArray[0], fArray[1], fArray[2]);
    var sDate = new Date(sArray[0], sArray[1], sArray[2]);

    var t = Math.abs(fDate.getTime() - sDate.getTime());
    var days = t / 1000 * 60 * 60 * 24;
    return days;
}


///设置页面中所有下拉控件的可见性；by 赵国伟
function SetDDlContrlVisible(isVisible) {
    var displayvalue = "";
    if (isVisible)
        displayvalue = "none";
    for (var i = 0; i < document.getElementsByTagName('select').length; ++i) {
        document.getElementsByTagName('select')[i].style.display = displayvalue;
    }
}

///获取指定下拉列表控件的选中值；by 赵国伟
function GetDDlObjectValue(idName) {

    if (document.getElementById(idName) != null && document.getElementById(idName).options != null) {
        if (document.getElementById(idName).options.selectedIndex > -1) {
            return document.getElementById(idName).options[document.getElementById(idName).options.selectedIndex].value;
        }
    }
    return "";
}

function GetDDlObjectText(idName) {
    if (document.getElementById(idName) != null && document.getElementById(idName).options != null) {
        if (document.getElementById(idName).options.selectedIndex > -1) {

            return document.getElementById(idName).options[document.getElementById(idName).options.selectedIndex].text;
        }
    }
    return "";
}

///====深拷贝一个Json对象结构 ========by 赵国伟；================================
function clone(jsonObj) {
    var buf;
    if (jsonObj instanceof Array) {
        buf = [];
        var i = jsonObj.length;
        while (i--) {
            buf[i] = clone(jsonObj[i]);
        }
        return buf;
    } else if (jsonObj instanceof Object) {
        buf = {};
        for (var k in jsonObj) {
            buf[k] = clone(jsonObj[k]);
        }
        return buf;
    } else {
        return jsonObj;
    }
}

////取窗口滚动条高度  by 赵国伟
function getScrollTop() {
    var scrollTop = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    return scrollTop;
}

//获得指定对象的左滚动条的宽度； by 赵国伟
function getScrollLeft(objName) {
    var scrollLeft = 0;
    if (objName != "") {
        scrollLeft = document.getElementById(objName).scrollLeft;
    }
    else {
        if (document.documentElement && document.documentElement.scrollLeft) {
            scrollLeft = document.documentElement.scrollLeft;
        }
        else if (document.body) {
            scrollLeft = document.body.scrollLeft;
        }
    }
    return scrollLeft;
}


//获取指定元素的在浏览器中距左边的实际距离；
function getLeft(e) {
    var offset = e.offsetLeft;
    if (e.offsetParent != null) offset += getLeft(e.offsetParent);
    return offset;
   
}

function getTop(e) {
    var offset = e.offsetTop;
    if (e.offsetParent != null) offset += getTop(e.offsetParent);
    return offset;
}

function isNoBadChar(str) {
    str = decodeURI(str);
    if (str == "") {
        return true;
    }
    var checkOK = "<>\"\'\\|$";
    var checkStr = str;
    var allValid = true;
    var j = 0;
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++) {
            if (ch == checkOK.charAt(j)) {
                break;
            }
        }
        if (j != checkOK.length) {
            allValid = false;
            break;
        }
    }
    if (!allValid) {
        return false;
    }
    return true;
}


///构造一个哈希表结构对象； by 赵国伟 2009-12-07
function HashTable() {
    this._hash = {};
    this._count = 0;
    this.add = function (key, value) {
        if (this._hash.hasOwnProperty(key)) return false;
        else { this._hash[key] = value; this._count++; return true; }
    }
    this.remove = function (key) { delete this._hash[key]; this._count--; }
    this.count = function () { return this._count; }
    this.items = function (key) { if (this.contains(key)) return this._hash[key]; }
    this.set = function (key, value) {
        if (this.contains(key))
            this._hash[key] = value;
        else
            this.add(key, value);
    }
    this.contains = function (key) { return this._hash.hasOwnProperty(key); }
    this.clear = function () { this._hash = {}; this._count = 0; }
    this.items2 = function (key) { if (this.contains(key)) return this._hash[key]; else return ""; }
    this.toString = function () {
        var str = "";
        return str;
    }
}

function openIeWindow(url, top, left, width, height) {
    window.open(url, "弹出窗口", "height=" + height + ",top=" + top + ",left=" + left + ",width=" + width + ",status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no");
}

///获得指定字符串的长度；汉字长度算2；
function GetLength(str) {
    var chineseRegex = /[^\x00-\xff]/g;
    return str.replace(chineseRegex, "**").length;
}

function subString(str, len, hasDot) {
    var newLength = 0;
    var newStr = "";
    var chineseRegex = /[^\x00-\xff]/g;
    var singleChar = "";
    var strLength = str.replace(chineseRegex, "**").length;
    for (var i = 0; i < strLength; i++) {
        singleChar = str.charAt(i).toString();
        if (singleChar.match(chineseRegex) != null) {
            newLength += 2;
        }
        else {
            newLength++;
        }
        if (newLength > len) {
            break;
        }
        newStr += singleChar;
    }

    if (hasDot && strLength > len) {
        newStr += "..";
    }
    return newStr;
}

//格式化指定的数字字符串；
function formatnumber(value, num) {
    var a, b, c, i;
    a = value.toString();
    b = a.indexOf(".");
    c = a.length;
    if (num == 0) {
        if (b != -1) {
            a = a.substring(0, b);
        }
    } else {
        if (b == -1) {
            a = a + ".";
            for (i = 1; i <= num; i++) {
                a = a + "0";
            }
        } else {
            a = a.substring(0, b + num + 1);
            for (i = c; i <= b + num; i++) {
                a = a + "0";
            }
        }
    }
    return a;
}


function ForDight(Dight, How) {
    Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
    return Dight;
}

//重写Js自带的toFixed方法： 因为toFixed（）在不同的浏览器中 实现不一样 导致精确度不一样； by 赵国伟；2009-12-15
Number.prototype.toFixed = function (s) {
    var s = (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
    return formatnumber(s, 2);
}


String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }

//指定位置插入字符串  by 赵国伟 2011-10-16
String.prototype.Insert = function (index, str) {
    return this.substring(0, index) + str + this.substr(index);
}

String.prototype.Remove = function (start, length) {
    var l = this.slice(0, start);
    var r = this.slice(start + length);
    return l + r;
}

//看数组是否包含某值
Array.prototype.Contains = function (str) {
    if (this.length == 0)
        return false;
    for (var index = 0; index < this.length; index++) {
        if (this[index] == str)
            return true;
    }
    return false;
}


//扩展方法 删除数组中指定元素； by 赵国伟 2011-09-14;
Array.prototype.remove = function (obj) {
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != obj) {
            this[n++] = this[i]
        }
    }
    this.length -= 1;
}
Array.prototype.removeEx = function (bianhao) {
    for (var i = 0, n = 0; i < this.length; i++) {
        if (i != bianhao) {
            this[n++] = this[i]
        }
    }
    this.length -= 1;
}

/**    
* 对Date的扩展，将 Date 转化为指定格式的String    
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符    
* 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)    
* eg:    
* (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423    
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04    
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04    
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04    
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18    
*/    
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份      
        "d+": this.getDate(), //日      
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时      
        "H+": this.getHours(), //小时      
        "m+": this.getMinutes(), //分      
        "s+": this.getSeconds(), //秒      
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度      
        "S": this.getMilliseconds() //毫秒      
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
} 

///检测指定的字符串是否为数字
function isDigit(s) {
    var patrn = /^[0-9]{1,20}$/;
    if (!patrn.exec(s))
        return false
    return true
}

function IsNumber(s)
{
   var patrn = /^\d+$/;
    if (!patrn.exec(s))
        return false
    return true;
}

///封装了AjaxPost请求的一系列处理流程； by 赵国伟 2010-03-25; 注：返回值 基于ReturnValue对象；
function AjaxPost(url, btnSummitName, postData, sucTips) {
    url += "&tttt=" + Math.random();
    $.ajax(
    {
        type: "POST",
        url: url,
        data: "jsonData=" + JSON.stringify(eval(postData)),
        dataType: "json",
        success: function (data) {
           // alert(data);
            var ret = data;
            if (ret.Result == 1) {
                if (sucTips == null || sucTips == "")
                    alert("提示：保存成功！");
                else
                    alert("提示：" + sucTips);
                location.reload();
            }
            else {
                alert(ret.Message);
                $("#" + btnSummitName).attr("disabled", false);
            }
        }
    });
}

function AjaxPostEx(url, btnSummitName, postData, sucTips) {
    url += "&tttt=" + Math.random();
    $.ajax(
    {
        type: "POST",
        url: url,
        data: postData,
        dataType: "json",
        success: function (data) {
            var ret = data;
            if (ret.Result == 1) {
                if (sucTips == null || sucTips == "")
                    alert("提示：保存成功！");
                else
                    alert("提示：" + sucTips);
                location.reload();
            }
            else {
                alert(ret.Message);
                $("#" + btnSummitName).attr("disabled", false);
            }

        }

    });
}

function AjaxPostEx2(url, btnSummitName, postData, callBack) {
    url += "&tttt=" + Math.random();
    $.ajax(
    {
        type: "POST",
        url: url,
        data: postData,
        dataType: "json",
        success: function (data) {
            var ret = data;
            callBack(ret);

        }

    });
}

function AjaxGet(url, btnSummitName, sucTips, isCloseTips) {
    url += "&tttt=" + Math.random();
    $.ajax(
    {
        type: "Get",
        url: url,
        dataType: "json",
        success: function (data) {
            var ret = data;
            if (isCloseTips == null || isCloseTips == false) {
                if (ret.Result == 1) {
                    if (sucTips == null || sucTips == "")
                        alert("提示：保存成功！");
                    else
                        alert("提示：" + sucTips);
                    location.reload();
                }
                else {
                    alert(ret.Message);
                    if(btnSummitName != null && btnSummitName != "")
                        $("#" + btnSummitName).attr("disabled", false);
                }
            }

        }

    });
}


function AjaxGetEx(url, btnSummitName,callback, isCloseLoadTips) {
    url += "&tttt=" + Math.random();
    if (isCloseLoadTips == null || IsLoadRunTips == undefined)
        isCloseLoadTips = false;
    IsLoadRunTips = !isCloseLoadTips;
    $.ajax(
    {
        type: "Get",
        url: url,
        dataType: "json",
        success: function (data) {
            callback(data);
            if (btnSummitName != null && btnSummitName != "")
               $("#" + btnSummitName).attr("disabled", false);
        }
    });
    IsLoadRunTips = true;
}

///同步方式获得指定地址的输出值[注意：提交方式为同步；非异步]
function GetUrlValueEx(url) {

    var result = "";
    var ajax = new Ajax.Request(url + "&tttt=" + Math.random(),
   { asynchronous: false, method: 'get', onSuccess: onSuccess,

       onFailure: function (xmlhttp) { alert("请求服务器端接口失败！请刷新重试或与管理员联系！"); }
   })
    function onSuccess(request) {

        result = request.responseText;
    }
    return result;
}


///为指定的弹出层 创建背景Frame 目的：遮住当前层区域涉及到的下拉控件； by 赵国伟 2010-04-27
function CreateFrameForDivToHideSelect(objPopDiv, z_index) {
    var o;

    if (oo('bgFrmOf' + objPopDiv) == null) {
        o = document.createElement('iframe');
        o.id = 'bgFrmOf' + objPopDiv;
        if (oo(objPopDiv).offsetParent != null)
            oo(objPopDiv).offsetParent.appendChild(o);  // $(objPopDiv)
        else {
            document.appendChild(o);
        }
    }
    else {
        o = oo('bgFrmOf' + objPopDiv);
    }
    o.style.position = "absolute";
    o.style.display = 'block';
    o.style.left = oo(objPopDiv).offsetLeft + "px";
    o.style.top = oo(objPopDiv).offsetTop + "px";
    o.style.width = oo(objPopDiv).offsetWidth + "px";
    o.style.height = oo(objPopDiv).offsetHeight + "px";
    o.style.zIndex = z_index;
}

///删除前面函数创建的iframe对象；
function DeleteFrameOfDivToHideSelect(objPopDiv) {
    if (oo('bgFrmOf' + objPopDiv) != null) {
        oo('bgFrmOf' + objPopDiv).style.display = "none";
    }
}

//检查输入字符是否有SQL相关的非法字符 陈明  2010-8-20
function CheckInputSql(strInput) {
    var instr = new Array("xp_cmdshell", ";", ",", "'", "\"", "drop", "and", "exec", "insert", "select", "delete", "update", "count(", "*", "chr(", "mid(", "master", "truncate", "char(", "declare");
    for (i = 0; i < instr.length; i++) {
        if (strInput.toString().indexOf(instr[i]) >= 0) {
            return true;
        }
    }
    return false;
}

//客户端实现后台REQUEST类似的功能 陈明  2010-9-1
function Request(strName) {
    var strHref = window.document.location.href;
    var intPos = strHref.indexOf("?");
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split("&");
    for (var i = 0; i < arrTmp.length; i++) {
        var arrTemp = arrTmp[i].split("=");
        if (arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1];
    }
    return "";
}
function RequestFromStr(strName, strHref) {
    var intPos = strHref.indexOf("?");

    var strRight = strHref.substr(intPos + 1);

    var arrTmp = strRight.split("&");
    for (var i = 0; i < arrTmp.length; i++) {
        var arrTemp = arrTmp[i].split("=");

        if (arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTmp[i].replace(arrTemp[0] + '=', '');
    }
    return "";
}




///将日期时间输出到指定的Span标签中； by 赵国伟 2010-09-13
function ShowTimeToSpan(objSpanName) {
    
    var today, hour, second, minute, year, month, date;
    var strDate;
    today = new Date();
    var n_day = today.getDay();
    switch (n_day) {
        case 0:
              strDate = "星期日"
              break;
        case 1:
              strDate = "星期一"
              break;
        case 2:
              strDate = "星期二"
              break;
        case 3:
              strDate = "星期三"
              break;
        case 4:
              strDate = "星期四"
              break;
        case 5:
              strDate = "星期五"
              break;
        case 6:
               strDate = "星期六"
              break;
        case 7:
              strDate = "星期日"
              break;
    }
    year = today.getFullYear();
    month = today.getMonth() + 1;
    date = today.getDate();

    hour = today.getHours();
    if (hour < 10)
        hour = "0" + hour;
    minute = today.getMinutes();
    if (minute < 10)
        minute = "0" + minute;
    second = today.getSeconds();
    if (second < 10)
        second = "0" + second;
    
    document.getElementById(objSpanName).innerHTML = "现在时间：" + year + "年 " + month + "月 " + date + "日 " + strDate + " " + hour + ":" + minute + ":" + second; //显示时间
    setTimeout("ShowTimeToSpan('" + objSpanName + "');", 1000); //设定函数自动执行时间为 1000 ms(1 s)
}


//打开或者关闭左侧菜单  by 赵国伟 2010-09-13
function SwitchFrame(leftObjName) {
    var obj = document.getElementById(leftObjName);
    var objTarget = document.getElementById("spStatus");
    if (obj.style.display == "") {
        obj.style.display = "none";
        objTarget.innerHTML = "<img src=\"/Manage/Images/openframe.gif\" width=\"9\" height=\"280\" border=\"0\" />";
        objTarget.title = "打开左侧菜单";

    }
    else {
        obj.style.display = "";
        objTarget.innerHTML = "<img src=\"/Manage/Images/closeframe.gif\" width=\"9\" height=\"280\" border=\"0\" />";
        objTarget.title = "关闭左侧菜单";
    }
}
function Login(userId, pwd) {
    if (userId == '' || userId == undefined) {
        alert('对不起!用户名不能为空');
        return false;
    }
    if (pwd == '' || pwd == undefined) {
        alert('对不起,密码不能空');
        return false;
    }

    $.ajax({
        url: 'PageBlock.ashx', type: 'post', dataType: 'text/html', data: { action: 'login', uid: userId, password: pwd },
        success: function(res) {
            if (res == 'ok') {

                var url = request('reUrl');
                if (url !== undefined && url != '' && url != null) {
                    window.location = unescape(url);
                } else {
                    //alert(window.location);
                    window.location = window.location;
                }
            } else {
                $('#loginState').css('display', '').text(res);
            }
        }
    });
}

function request(paras) {
    var url = location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf
        ("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {
        return "";
    } else {
        return returnValue;
    }
} 
function MyMarquee(Id) {
    var speed = 50//速度数值越大速度越慢
    var semo1 = document.getElementById("semo1_" + Id);
    var semo2 = document.getElementById("semo2_" + Id);
    var semo = document.getElementById("semo_" + Id);
    semo2.innerHTML = semo1.innerHTML
    function Marquee() {
        if (semo2.offsetWidth - semo.scrollLeft <= 0)
            semo.scrollLeft -= semo1.offsetWidth
        else {
            semo.scrollLeft++
        }
    }
    var MyMar = setInterval(Marquee, speed)
    semo.onmouseover = function() { clearInterval(MyMar) }
    semo.onmouseout = function() { MyMar = setInterval(Marquee, speed) }

}

/// 判断指定的字符串是否为中文！
function isChinese(str) {
    var reg = /^[\u0391-\uFFE5]+$/;    
    if (!reg.test(str)) {
        return false;
    }
    return true;
}

///检查邮件地址格式是否正确；
function IsEmail(str) {
    if (!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str))) {
        return false;
    }
    return true;
}



//添加到收藏夹
function AddFavorite(url, title) {
    if (document.all) {
        window.external.addFavorite(url, title);
    }
    else if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    }
    else {
        alert("提示：您使用的浏览器暂不支持此功能！");
    }
}

//为每个页面注册一个事件；
document.onkeydown = function (e) {
    var e = window.event ? window.event : e;
    var a = e.srcElement || e.target;
    if (e.keyCode == 13 && a.type != "textarea") {
        $("#btnSearch").click();
        e.cancelBubble = true;
        e.returnValue = false;
    }
}
///设置默认回车触发的按钮
function SetEnterBtn(btnId) {
    eval(
     "   function keydown(e) { var currKey = 0, e = e || event;  currKey = e.keyCode || e.which || e.charCode; if (currKey == 13) {      document.getElementById(\"" + btnId + "\").click(); }  }  document.onkeydown = keydown;   "
    );
   
}

function GetEditorHTMLContents(EditorName) {
    var oEditor = FCKeditorAPI.GetInstance(EditorName);
    return (oEditor.GetXHTML(true));
}

//向指定的多文本编辑框插入一段Html代码；
function InsertEditorHTML(EditorName, html) {
    var oEditor = FCKeditorAPI.GetInstance(EditorName);
    oEditor.InsertHtml(html);
}

///获取多文本编辑框
function GetEditor(txtObject, width, height, styleName) {
    if (width == null) width = "100%";
    if (height == null) height = 300;
    if (styleName == null) styleName = "Basic";

    var oFCKeditor = new FCKeditor(txtObject);
    oFCKeditor.BasePath = "/FckEditor/";
    oFCKeditor.Width = width;
    oFCKeditor.Height = height;
    oFCKeditor.ToolbarSet = styleName;
    oFCKeditor.ReplaceTextarea();

}


function alert2(msg) {
    GetPopupDiv(400, 300, "#e2e2e2", "警告", function () {
        var html = new Array();
        html.push("<table width=\"400\" height=\"50\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
        html.push("  <tr>");
        html.push("    <td width=\"127\" align=\"right\"><img src=\"/Manage/Images/warning.png\" width=\"64\" height=\"64\" /></td>");
        html.push("    <td width=\"273\" style=\"font-size:14px;color:gray;\">" + msg + "</td>");
        html.push("  </tr>");
        html.push("  <tr>");
        html.push("    <td colspan=\"2\" align=\"center\"> <input name=\"btnClose\" type=\"button\" id=\"btnClose\" value=\"关闭窗口\" onClick=\"yesOther(false)\"  class=\"btn2\"></td>");
        html.push("  </tr>");
        html.push("</table>");
        return html.join("");
    }, "divOfAlert", true, true);
}



//两个浮点数相乘的方法。//摘自：blog.csdn.net/Feiin/article/details/2885814     
function dcmMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
//两个浮点数相加的方法。//摘自：blog.csdn.net/Feiin/article/details/2885814  
function dcmAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    return (dcmMul(arg1, m) + dcmMul(arg2, m)) / m;
}

//乘法
Number.prototype.Mul = function (arg) {
    return dcmMul(this, arg);
}
//除法；
Number.prototype.Div = function (arg) {
    return dcmMul(this, 1 / arg)
}
//加法
Number.prototype.Add = function (arg) {
    return dcmAdd(this, arg);
}
//减法；
Number.prototype.Sub = function (arg) {
    return dcmAdd(this, -arg);
}


function $G(objName) {
    return encodeURIComponent($(objName).val()).replace(/%0D/g, "\r").replace(/%0A/g, "\n");
}

///加入收藏夹
function AddFavorite(url, sitename) {
    if (document.all) {
        window.external.addFavorite(url, sitename);
    }
    else if (window.sidebar) {
        window.sidebar.addPanel(sitename, url, "");
    }
    else {
        alert("对不起，您的浏览器不支持此操作！\r\n请您使用菜单栏或Ctrl+D收藏本站。");
    }
} 
